package com.quanquan.user.controller;

import DTO.PageDTO;
import DTO.user.UserDTO;
import DTO.user.UserInfoDTO;
import base.BaseController;
import base.UserConst;
import com.alibaba.fastjson.JSONObject;
import com.quanquan.user.configBeans.Weixin;
import com.quanquan.user.dto.IdDTO;
import com.quanquan.user.entity.User;
import com.quanquan.user.exception.UserException;
import com.quanquan.user.request.OpenidRequestBody;
import com.quanquan.user.request.RegisterRequestBody;
import com.quanquan.user.request.UserRequestBody;
import com.quanquan.user.service.UserService;
import com.quanquan.user.service.app.AppUserService;
import enums.ResCodeEnum;
import enums.UserResCodeEnum;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import request.PageRequestBody;
import utils.MobileUtil;
import utils.StringUtil;
import utils.VerifyCodeUtil;
import web.response.ResultBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 功能描述:
 *
 * @ClassName: UserController
 * @Author: xiaoqianh丶
 * @Date: 2019-02-27 14:41
 * @Version: V1.0
 */
@Log4j2
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {
    private static final String NOTUSER = "未找到该会员";
    private static final String STRING = "?";
    private Logger logger = LoggerFactory.getLogger(this.getClass());


    private final static String LOGIN = "loginNum-";

    private static final Integer EXPIRE = 120;

    private final AppUserService appUserService;

    private final UserService userService;

    private final StringRedisTemplate redisTemplate;

    private final Weixin weixin;

    @Value("${openId-params.openIdUrl}")
    private  String serverurl;

    @Autowired
    public UserController(AppUserService appUserService, UserService userService, StringRedisTemplate redisTemplate, Weixin weixin) {
        this.appUserService = appUserService;
        this.userService = userService;
        this.redisTemplate = redisTemplate;
        this.weixin = weixin;
    }

    /**
     * 注册登录接口
     * 1.验证手机号
     * 2.根据手机号发送短信验证码
     * 3.将验证码存到redis中key值是电话号码
     */
    @PostMapping("/check_code")
    @ResponseBody
    public ResultBody checkValidaNum(@RequestBody UserRequestBody requestBody) {
        //用户输入的随机码
        String code = requestBody.getValidaCode().toLowerCase();
        //随机码
        String validaCode = redisTemplate.opsForValue().get(LOGIN + code);
        //查看缓存中的随机码
        if (StringUtils.isEmpty(validaCode)) {
            return new ResultBody(UserResCodeEnum.WRONG_CODE.getCode(), UserResCodeEnum.WRONG_CODE.getMsg());
        }
        String phone = requestBody.getPhone();
        //校验手机号的合法性
        if (!MobileUtil.isPhoneLegal(phone)) {
            return new ResultBody(UserResCodeEnum.INCORRECT_PHONE.getCode(), UserResCodeEnum.INCORRECT_PHONE.getMsg());
        }
        //校验随机是否正确
        if (!code.equals(validaCode)) {
            return new ResultBody(UserResCodeEnum.WRONG_CODE.getCode(), UserResCodeEnum.WRONG_CODE.getMsg());
        }
        //发送短信
        Boolean result = appUserService.sendMsg(phone);
        if (result) {
            return new ResultBody(UserResCodeEnum.CODE_SUCCESS.getCode(), UserResCodeEnum.CODE_SUCCESS.getMsg());
        }
        return new ResultBody(UserResCodeEnum.CODE_FAIL.getCode(), UserResCodeEnum.CODE_FAIL.getMsg());
    }



    /**
     * 注册登录接口(微信小程序)
     * 2.根据手机号发送短信验证码
     */
    @PostMapping("/send_message")
    @ResponseBody
    public ResultBody sendMessage(@RequestBody UserRequestBody requestBody) {


        String phone = requestBody.getPhone();
        //校验手机号的合法性
        if (!MobileUtil.isPhoneLegal(phone)) {
            return new ResultBody(UserResCodeEnum.INCORRECT_PHONE.getCode(), UserResCodeEnum.INCORRECT_PHONE.getMsg());
        }

        //发送短信
        Boolean result = appUserService.sendMsg(phone);
        if (result) {
            return new ResultBody(UserResCodeEnum.CODE_SUCCESS.getCode(), UserResCodeEnum.CODE_SUCCESS.getMsg());
        }
        return new ResultBody(UserResCodeEnum.CODE_FAIL.getCode(), UserResCodeEnum.CODE_FAIL.getMsg());
    }




    /**
     * 获取验证码图片
     */
    @GetMapping("/valida_code")
    @ResponseBody
    public void getValidationCode() {
        try {
            ServletOutputStream outputStream = this.response.getOutputStream();
            VerifyCodeUtil.drawImage(outputStream);
            String code = VerifyCodeUtil.getCode();
            System.out.println(code);
            //向redis中存验证码，保存时间1分钟
            redisTemplate.opsForValue().set(LOGIN + code, code, EXPIRE, TimeUnit.SECONDS);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }




    /**
     * 用户登录注册
     *
     * @param requestBody
     */
    @PostMapping("/login")
    @ResponseBody
    public ResultBody doLogin(@RequestBody UserRequestBody requestBody) {
        String msgsCode = requestBody.getMsgsCode();
        String phone = requestBody.getPhone();
        String headimg = requestBody.getHeadimg();
        System.out.println(headimg);
        //根据号码从缓存中获取验证码
            String code = appUserService.getSMSCode(phone);
            if (StringUtils.isEmpty(code)) {
                return new ResultBody(UserResCodeEnum.WRONG_CODE.getCode(), UserResCodeEnum.WRONG_CODE.getMsg());
            } else if (!msgsCode.equals(code)) {
                return new ResultBody(UserResCodeEnum.WRONG_CODE.getCode(), UserResCodeEnum.WRONG_CODE.getMsg());
            }

            //防止重复提交数据在并发的情况下
        boolean result = appUserService.removeSMSCode(phone);

        if(result){
            User user = userService.loginOrRegistered(requestBody, phone);
            if(user == null ){
                return new ResultBody(UserResCodeEnum.FROZEN_ACCOUNT.getCode(), UserResCodeEnum.FROZEN_ACCOUNT.getMsg());
            }
            return new ResultBody(UserResCodeEnum.LOGIN_SUCCESS.getCode(), UserResCodeEnum.LOGIN_SUCCESS.getMsg(), user);

        }
        return new ResultBody(UserResCodeEnum.WRONG_CODE.getCode(), UserResCodeEnum.WRONG_CODE.getMsg());
    }

    /**
     * 后台手动添加会员
     * @param requestBody
     * @return
     */
    @PostMapping("/register")
    @ResponseBody
    public ResultBody backRegister(@RequestBody UserRequestBody requestBody) {
        if (StringUtil.isEmpty(requestBody.getPhone())) {
            return new ResultBody(ResCodeEnum.UG_PAEAMES.getCode(),ResCodeEnum.UG_PAEAMES.getMsg());
        }
        User userByPhone = userService.findUserByPhone(requestBody.getPhone());
        if (null != userByPhone) {
            return new ResultBody(-2,"用户已存在");
        }
        User user = userService.loginOrRegistered(requestBody, requestBody.getPhone());
        if (null != user) {
            return new ResultBody(ResCodeEnum.SUCCESS.getCode(),ResCodeEnum.SUCCESS.getMsg(),user);
        }
        return new ResultBody(ResCodeEnum.FAIL.getCode(),ResCodeEnum.FAIL.getMsg());

    }

    /**
     * 分页查询会员列表
     *
     * @param requestBody
     * @return
     */
    @PostMapping("/query")
    @ResponseBody
    public ResultBody getUserList(@RequestBody PageRequestBody requestBody) {
        PageDTO<User> pageDTO = null;
        try {
            pageDTO = userService.findAllUsers(requestBody);
        } catch (UserException e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
        }
        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), pageDTO);
    }


    /**
     * 根据会员id查询会员信息
     *
     * @param requestBody
     * @return
     */
    @PostMapping("/edit")
    @ResponseBody
    public ResultBody getUser(@RequestBody UserRequestBody requestBody) {
        String userId = requestBody.getUserId();
        User user;
        try {
            user = userService.getUserById(userId);
        } catch (UserException e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
            return new ResultBody(ResCodeEnum.FAIL.getCode(), "您暂未登录", NOTUSER);
        }

        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), user);
    }

    /**
     * 更新用户信息
     *
     * @param requestBody
     * @return
     */
    @PostMapping("/update")
    @ResponseBody
    public ResultBody updateUserInfo(@RequestBody UserRequestBody requestBody) {
        String userId = requestBody.getUserId();
        String msg;
        try {
            msg = userService.updateUserInfo(requestBody, userId);
        } catch (UserException e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
            return new ResultBody(ResCodeEnum.FAIL.getCode(), ResCodeEnum.FAIL.getMsg(), NOTUSER);
        }
        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), msg);
    }


    /**
     * 获取用户的openid（微信公众号）
     *
     * @param requestBody
     * @return
     */
    @PostMapping("/get_openid")
    @ResponseBody
    public ResultBody getOpenid(@RequestBody OpenidRequestBody requestBody) {
        if (StringUtils.isEmpty(requestBody.getCode())) {
            return new ResultBody(UserResCodeEnum.UG_PAEAMES.getCode(), "获取用户openid缺少code");
        }
        //openid
        requestBody.setType(1);
        String openidInfo = userService.getOpenidInfo(requestBody);

        if (StringUtils.isEmpty(openidInfo)) {
            return new ResultBody(ResCodeEnum.UG_OPENID.getCode(), ResCodeEnum.UG_OPENID.getMsg(), null);
        }

        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), openidInfo);
    }

    @PostMapping("get_by_phone")
    @ResponseBody
    public ResultBody getByMobile(@RequestBody UserRequestBody requestBody) {
        String mobile = requestBody.getPhone();
        if (StringUtil.isEmpty(mobile)) {
            return new ResultBody(ResCodeEnum.UG_PAEAMES.getCode(),ResCodeEnum.UG_PAEAMES.getMsg());
        }
        User user = userService.findUserByPhone(mobile);
        if (null != user) {
            Integer freeze = user.getFreeze();
            if(freeze ==0){
                return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), user);

            }
            return new ResultBody(UserResCodeEnum.FROZEN_ACCOUNT.getCode(), UserResCodeEnum.FROZEN_ACCOUNT.getMsg(), user);
        }
        return new ResultBody(ResCodeEnum.FAIL.getCode(), "用户暂未注册");
    }

    @PostMapping("get_by_card")
    @ResponseBody
    public ResultBody getByCard(@RequestBody UserRequestBody requestBody) {
        String memberCardNum = requestBody.getMemberCardNum();
        if (StringUtil.isEmpty(memberCardNum)) {
            return new ResultBody(ResCodeEnum.UG_PAEAMES.getCode(),ResCodeEnum.UG_PAEAMES.getMsg());
        }
        User user = userService.findUserByCard(memberCardNum);
        if (null != user) {
            Integer freeze = user.getFreeze();
            if(freeze ==0){
                return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), user);

            }
            return new ResultBody(UserResCodeEnum.FROZEN_ACCOUNT.getCode(), UserResCodeEnum.FROZEN_ACCOUNT.getMsg(), user);
        }
        return new ResultBody(ResCodeEnum.FAIL.getCode(), "用户暂未注册");
    }


    /**
     * 获取微信公众号openid
     *
     * @param request
     * @param code
     * @param redirect
     * @return
     */
    @GetMapping("/get_wx_openid")
    public String getWXOpenid(HttpServletRequest request, String code, String redirect) {
        StringBuilder redUrl = new StringBuilder().append("redirect:");
        if (StringUtils.isEmpty(code)) {
            String localUrl =
                    request.getScheme() + "://" +serverurl+
                            request.getRequestURI() +
                            STRING + request.getQueryString();

            redUrl.append(weixin.createOauthUrlForCode(localUrl));
        } else {
            String openid = weixin.getOpenidFromCode(code);
            try {
                redirect = URLDecoder.decode(redirect, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            redUrl.append(redirect);
            if (redirect.contains(STRING)) {
                redUrl.append("&");
            } else {
                redUrl.append(STRING);
            }
            redUrl.append("openid=").append(openid);
        }
        return redUrl.toString();
    }

    /**
     * 查看用户是否关注微信公众号
     *
     * @param  userRequestBody
     * @return
     */
    @PostMapping("/check_fous_on")
    @ResponseBody
    public ResultBody checkFousOn(@RequestBody UserRequestBody userRequestBody) {
        //获取acceass_token
        String weChatToken = userService.getWeChatToken();
        String wxOpenid = userRequestBody.getWxOpenid();
        if(StringUtil.isEmpty(wxOpenid)){
            return new ResultBody(ResCodeEnum.FAIL.getCode(), ResCodeEnum.FAIL.getMsg());
        }
        if (StringUtils.isEmpty(weChatToken)) {
            return new ResultBody(ResCodeEnum.UG_ACCESS_TOKEN.getCode(), ResCodeEnum.UG_ACCESS_TOKEN.getMsg(), null);
        }
        //验证用户是否关注过微信公众号
        boolean checkPower = userService.checkPower(wxOpenid, weChatToken);
        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), checkPower);
    }

    /**
     * 从微信获取用户电话号码(微信小程序)
     *
     * @return
     */
    @PostMapping("/getParkingPhone")
    @ResponseBody
    public ResultBody getParkingPhone(@RequestBody RegisterRequestBody requestBody) {
        String result = userService.getParkingMemberPhone(requestBody);
        if (result == null) {
            return new ResultBody(UserResCodeEnum.AUTH_TIME_OUT.getCode(), UserResCodeEnum.AUTH_TIME_OUT.getMsg());
        } else {
            JSONObject json = JSONObject.parseObject(result);
            String mobile = json.getString(UserConst.FIELDS.PURE_PHONE);
            return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), mobile);
        }
    }


    /**
     * 从微信获取用户电话号码
     *
     * @return
     */
    @PostMapping("/getPhone")
    @ResponseBody
    public ResultBody getPhone(@RequestBody OpenidRequestBody requestBody) {

        String result = userService.getMemberPhone(requestBody);
        if (result == null) {
            return new ResultBody(UserResCodeEnum.AUTH_TIME_OUT.getCode(), UserResCodeEnum.AUTH_TIME_OUT.getMsg());
        } else {
            JSONObject json = JSONObject.parseObject(result);
            String mobile = json.getString(UserConst.FIELDS.PURE_PHONE);
            return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), mobile);
        }
    }

    /**
     * 根据条件查询会员
     * @param requestBody
     * @return
     */
    @PostMapping("/query_select")
    @ResponseBody
    public ResultBody selectQuery(@RequestBody UserRequestBody requestBody) {
        PageDTO<User> users = userService.queryCondition(requestBody);
        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), users);

    }

    /**
     * 退出账号 解除绑定关系
     * @return
     */
    @PostMapping("/leave")
    @ResponseBody
    public ResultBody leaveApplication (@RequestBody UserRequestBody requestBody){
        String source = requestBody.getSource();
        String userId = requestBody.getUserId();
        boolean relationShip = userService.unbindReleationShip(source, userId);
        if(relationShip){
            return new ResultBody(ResCodeEnum.SUCCESS.getCode(), "解绑成功");
        }
        return new ResultBody(ResCodeEnum.FAIL.getCode(), "解绑失败");
    }

    @RequestMapping(path = "/getJsSignPackage", method = RequestMethod.POST)
    @ResponseBody
    public ResultBody getJsSignPackage(@RequestBody UserRequestBody requestBody) {
        String weChatToken = userService.getWeChatToken();
        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), "SUCCESS", weixin.getSignPackage(requestBody.getUrl(),weChatToken));
    }

    @PostMapping("/weixin_user_info")
    @ResponseBody
    public ResultBody  getWeChatPersionInfo(@RequestBody UserRequestBody requestBody){
        String wxOpenid = requestBody.getWxOpenid();
        Map<String, String> weChatPersionInfo = userService.getWeChatPersionInfo(wxOpenid);
        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), "SUCCESS", weChatPersionInfo);

    }

    /**
     * 通过idList查找商户列表
     * @param idDTO
     * @return
     */
    @PostMapping("/query_by_id_list")
    @ResponseBody
    public UserInfoDTO queryByIdList(@RequestBody IdDTO idDTO){

        UserInfoDTO userInfoDTO = new UserInfoDTO();

        userInfoDTO.setUserDTOS(userService.queryByIdList(idDTO.getForeignKeyIds()));
        return userInfoDTO;
    }

    @PostMapping("/queryListByKeyword")
    @ResponseBody
    public UserInfoDTO queryListByKeyword(@RequestBody IdDTO idDTO) {
        List<User> users = userService.findListByKeyword(idDTO.getKeyWord());
        if(users.size()<=0){
            return null;
        }
        UserInfoDTO userInfoDTO = new UserInfoDTO();
        List<UserDTO> userDTOList=  new ArrayList<>();
        users.forEach(user -> {
            UserDTO userDTO = new UserDTO();
            BeanUtils.copyProperties(user, userDTO);
        });
        userInfoDTO.setUserDTOS(userDTOList);
        return userInfoDTO;
    }

    @PostMapping("/query_keyword")
    @ResponseBody
    public UserInfoDTO queryKeyword (@RequestBody IdDTO idDTO){
        List<User> users = userService.findListByKeyword(idDTO.getKeyWord());
        if(users.size()<=0){
            return null;
        }

        List<UserDTO> userDTOList=  new ArrayList<>();

        User user = users.get(0);
        UserDTO userDTO = new UserDTO();
        //通过映射关系来赋值 //TODO 断点看一下
        BeanUtils.copyProperties(user, userDTO);
        userDTOList.add(userDTO);
        UserInfoDTO userInfoDTO = new UserInfoDTO();
        userInfoDTO.setUserDTOS(userDTOList);
        return userInfoDTO;
    }


    /**
     * 设置用户冻结
     * @param requestBody
     * @return
     */
    @PostMapping("/frozen_account")
    @ResponseBody
    public ResultBody changeFrozenAccount (@RequestBody UserRequestBody requestBody){
        String userId = requestBody.getUserId();
        if (StringUtil.isEmpty(userId)) {
            return new ResultBody(ResCodeEnum.UG_PAEAMES.getCode(),ResCodeEnum.UG_PAEAMES.getMsg());
        }
        try {
            User result = userService.changeUserStatus(userId);
            return new ResultBody(ResCodeEnum.SUCCESS.getCode(),ResCodeEnum.SUCCESS.getMsg(),result);
        } catch (UserException e) {
            log.error(e.getMessage());
            return new ResultBody(ResCodeEnum.FAIL.getCode(),ResCodeEnum.FAIL.getMsg());
        }
    }


    //获取用户的手机号
    @PostMapping("/getMemberMobile")
    @ResponseBody
    public ResultBody getMemberMobile(@RequestBody RegisterRequestBody requestBody) {
        //获取用户的手机号
        String result = appUserService.getMobileBySessionKey(requestBody);
        if (result == null) {
            return new ResultBody(UserResCodeEnum.AUTH_TIME_OUT.getCode(), UserResCodeEnum.AUTH_TIME_OUT.getMsg());
        } else {
            JSONObject json = JSONObject.parseObject(result);
            String mobile = json.getString(UserConst.FIELDS.PURE_PHONE);
            return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), mobile);
        }
    }

    //获取用户的opneid并注册(小程序)
    @PostMapping("/openid")
    @ResponseBody
    public ResultBody getOpenid(@RequestBody RegisterRequestBody requestBody) {
        if (StringUtils.isEmpty(requestBody.getCode())) {
            new ResultBody(UserResCodeEnum.UG_PAEAMES.getCode(), UserResCodeEnum.UG_PAEAMES.getMsg());
        }
        requestBody.setType(1);
        String openId = userService.getOpenId(requestBody);
        if (openId != null) {
            return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), openId);
        }
        return new ResultBody(ResCodeEnum.FAIL.getCode(), ResCodeEnum.FAIL.getMsg());
    }

    /**
     * 获取用户的openid（停车小程序）
     *
     * @param requestBody
     * @return
     */
    @PostMapping("/get_parking_openid")
    @ResponseBody
    public ResultBody getParkingOpenid(@RequestBody RegisterRequestBody requestBody) {
        if (StringUtils.isEmpty(requestBody.getCode())) {
            return new ResultBody(UserResCodeEnum.UG_PAEAMES.getCode(), "获取用户openid缺少code");
        }
        //openid
        requestBody.setType(2);
        String openidInfo = userService.getOpenId(requestBody);
        if (StringUtils.isEmpty(openidInfo)) {
            return new ResultBody(ResCodeEnum.UG_OPENID.getCode(), ResCodeEnum.UG_OPENID.getMsg(), null);
        }
        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), openidInfo);
    }
    @PostMapping("/user_info")
    @ResponseBody
    public ResultBody  getUserPhone(@RequestBody UserRequestBody requestBody){
        String wxOpenid = requestBody.getWxOpenid();
        User userPhone = userService.getUserPhone(wxOpenid);
        if(userPhone == null ){
            return new ResultBody(ResCodeEnum.FAIL.getCode(),ResCodeEnum.FAIL.getMsg());
        }
        return new ResultBody(ResCodeEnum.SUCCESS.getCode(),ResCodeEnum.SUCCESS.getMsg(),userPhone);
    }

    @PostMapping("/check_balance")
    @ResponseBody
    public Boolean checkUserBalance (@RequestBody IdDTO idDTO){
        String userId = idDTO.getForeignKeyId();
        Integer price = idDTO.getIntegral();
        return userService.checkBalance(userId, price);
    }

    /**
     * 通openid
     * @param requestBody
     * @return
     */
    @PostMapping("/user_openid")
    @ResponseBody
    private ResultBody findUserByOpenId(@RequestBody UserRequestBody requestBody){
        String openid = requestBody.getOpenid();
        System.out.println("openid...."+openid);
        if(StringUtil.isEmpty(openid)){
            return new ResultBody(ResCodeEnum.FAIL.getCode(), ResCodeEnum.FAIL.getMsg());
        }
        User user = userService.findUserByOpeId(openid,requestBody.getSource());
        System.out.println("user....."+user);
        if(user==null){
            return new ResultBody(ResCodeEnum.FAIL.getCode(), ResCodeEnum.FAIL.getMsg());

        }
        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), user);

    }


    @PostMapping("/login_applet")
    @ResponseBody
    public ResultBody wxLogin (@RequestBody UserRequestBody requestBody){
        String phone = requestBody.getPhone();
        if(StringUtil.isEmpty(phone)){
            return new ResultBody(UserResCodeEnum.LOGIN_FAIL_PHONE.getCode(), UserResCodeEnum.LOGIN_FAIL_PHONE.getMsg(),"缺少电话号码");
        }
        User user = userService.loginOrRegistered(requestBody, phone);
        if(user == null ){
            return new ResultBody(UserResCodeEnum.FROZEN_ACCOUNT.getCode(), UserResCodeEnum.FROZEN_ACCOUNT.getMsg());
        }
        return new ResultBody(UserResCodeEnum.LOGIN_SUCCESS.getCode(), UserResCodeEnum.LOGIN_SUCCESS.getMsg(), user);
    }


    @PostMapping("/update_memberCard")
    @ResponseBody
    public ResultBody updateMemberCard (@RequestBody UserRequestBody requestBody){
        String s = userService.updateMembercard();
        return new ResultBody(UserResCodeEnum.LOGIN_SUCCESS.getCode(), UserResCodeEnum.LOGIN_SUCCESS.getMsg(), s);
    }

    /**
     * 根据会员id查询会员信息
     *
     * @param requestBody
     * @return
     */
    @PostMapping("/qurey_by_user_id")
    @ResponseBody
    public ResultBody queryByUserId(@RequestBody UserRequestBody requestBody) {
        String userId = requestBody.getUserId();
//        com.quanquan.user.dto.UserDTO user;
        User user;
        com.quanquan.user.dto.UserDTO userDTO = new com.quanquan.user.dto.UserDTO();
        try {
//            user = userService.getUserAndLevelImageById(userId);
            user = userService.getUserById(userId);
            BeanUtils.copyProperties(user,userDTO);
        } catch (UserException e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
            return new ResultBody(ResCodeEnum.FAIL.getCode(), "请您先授权登录", NOTUSER);
        }

        return new ResultBody(ResCodeEnum.SUCCESS.getCode(), ResCodeEnum.SUCCESS.getMsg(), userDTO);
    }


}
